package com.distributeredis.redis_springboot.springapachehttpclienthttpconnectionresttemplate.httpclient.study3.testcontroller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.stream.Collectors;

/**
 * 使用HttpURLConnection执行Get和Post
 */
@RestController
@RequestMapping("/connection")
public class HttpUrlConnection {

    @GetMapping("/test1")
    public Object test1() {
        try {
            //对应GET请求，要把请求信息拼接在url后面
            URL url = new URL("http://localhost:8080/user/testGet");
            //调用url的openConnection()方法,获得连接对象
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //设置HttpURLConnection的属性
            conn.setRequestMethod("GET");
            conn.setReadTimeout(5000);
            conn.setConnectTimeout(5000);
            //只是建立一个连接, 并不会发送真正http请求  (可以不调用)
            conn.connect();
            //通过响应码来判断是否连接成功
            if (conn.getResponseCode() == 200) {
                //获得服务器返回的字节流
                InputStream is = conn.getInputStream();
                String result = new BufferedReader(new InputStreamReader(is))
                        .lines().collect(Collectors.joining("\n"));
                return result;
            }
            conn.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
